from google.appengine.ext import db

from gaev import exceptions

def get_object_specification(object):
	from gaev.model import BaseModel
	from gaev.model import EntitySet
	params={}
	if isinstance(object, BaseModel):
		params['entity_key']=object.key()
	elif isinstance(object, EntitySet):
		params['model_name']=object.model.__name__
		if hasattr(object, 'restrictor'):
			params['model_restrictor']=object.restrictor.get_specifier()
			
	else:
		raise exceptions.ArgumentError('Trying to get action URL for unsupported object.')
	return params

def get_entity_set_by_name(name):
	try:
		return db.class_for_kind(name).entities()
	except db.KindError:
		raise exceptions.MissingModelError

def get_object_from_specification(spec):
	print '##spec##', spec
	if 'entity_key' in spec:
		return db.get(spec['entity_key'])
	if 'entity_model_name' in spec and 'entity_human_key' in spec:
		entity_set=get_entity_set_by_name(spec['entity_model_name'])
		return entity_set.get_by_human_key(spec['entity_human_key'])
	if 'model_name' in spec:
		entity_set=get_entity_set_by_name(spec['model_name'])
		if 'model_restrictor' in spec:
			from gaev.model.restrictor import get_restricted_entity_set
			entity_set=get_restricted_entity_set(entity_set, spec['model_restrictor'])
		return entity_set
	return None
	


def get_action_url(action, object=None, key=None, model=None, human_key=None, user_params={}):
	if isinstance(action, str):
		action_name=action
		action_object=None
	else:
		action_name=action.get_name()
		action_object=action

	url="/%s/?" % action_name
	
	if object:
		params=get_object_specification(object)
	elif key:
		params={'entity_key': key}
	elif model and human_key:
		if isinstance(model, str):
			model_name=model
		else:
			model_name=model.__name__
		params={'entity_model_name': model_name, 'entity_human_key': human_key}
	else:
		params={}
	if action_object:
		params.update(action_object.get_nondefault_params())
	params.update(user_params)
	
	if len(params)>0:
		from urllib import urlencode
		url+=urlencode(params)
	return url 
